<template>
  <div class="chat-container">
    <!-- 会话管理侧边栏 -->
    <div v-if="showSessionSidebar" class="session-sidebar">
      <div class="sidebar-header">
        <h3>会话列表</h3>
        <n-button quaternary circle size="small" @click="handleCreateNewSession">
          <n-icon><AddOutline /></n-icon>
        </n-button>
      </div>
      <div class="session-list">
        <div 
          v-for="session in chatStore.sessions" 
          :key="session.id"
          :class="['session-item', { active: session.id === chatStore.currentSessionId }]"
          @click="chatStore.switchSession(session.id)"
        >
          <div class="session-title">{{ session.title }}</div>
          <div class="session-info">
            <span class="message-count">{{ session.messageCount }} 条消息</span>
            <span class="last-active">{{ formatTime(session.lastActiveAt) }}</span>
          </div>
          <div class="session-actions">
            <n-button quaternary circle size="tiny" @click.stop="chatStore.deleteSession(session.id)">
              <n-icon><TrashOutline /></n-icon>
            </n-button>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-body" ref="chatBodyRef">
      <!-- 错误提示 -->
      <div v-if="hasError" class="error-banner">
        <n-alert type="error" :title="chatStore.error?.message" closable @close="chatStore.clearError">
        </n-alert>
      </div>

      <div class="message-container">
        <!-- 欢迎消息 -->
      <div v-if="currentSessionMessages.length === 0" class="empty-state-container">
        <p class="welcome-text">开始一段新的对话吧！</p>
      </div>

      <!-- 消息列表 -->
      <ChatMessage
        v-for="(message, index) in currentSessionMessages"
        :key="message.id"
        :message="message"
        :index="index"
        :user-id="userStore.userId"
        :messages-length="currentSessionMessages.length"
        @resend-message="handleResendMessage"
        @edit-message="handleEditMessage"
        @edit-message-submit="handleEditMessageSubmit"
        @update-message-status="handleUpdateMessageStatus"
        :safe-markdown-render="renderMarkdown"
      />

        <!-- 移除全局加载指示器，避免与ChatMessage中的加载动画重复 -->
      </div>
    </div>

    <!-- 图片预览区域 -->
    <div v-if="selectedImages.length > 0" class="image-preview-container">
      <div class="image-preview-list">
        <div v-for="(img, index) in selectedImages" :key="index" class="image-preview-item">
          <img :src="img" alt="预览" class="preview-image" />
          <div class="image-remove-btn" @click="removeImage(index)">
            <n-icon size="16">
              <CloseOutline />
            </n-icon>
          </div>
        </div>
      </div>
      <div class="image-count-tip">
        已选择 {{ selectedImages.length }}/3 张图片
      </div>
    </div>

    <!-- 文档预览区域 -->
    <div v-if="selectedDocuments.length > 0" class="document-preview-container">
      <div class="document-preview-list">
        <div v-for="(doc, index) in selectedDocuments" :key="index" class="document-preview-item">
          <div class="document-info">
            <n-icon size="16">
              <DocumentTextOutline />
            </n-icon>
            <span class="document-name">{{ getDocumentName(doc) }}</span>
          </div>
          <div class="document-remove-btn" @click="removeDocument(index)">
            <n-icon size="16">
              <CloseOutline />
            </n-icon>
          </div>
        </div>
      </div>
      <div class="document-count-tip">
        已选择 {{ selectedDocuments.length }} 个文档
      </div>
    </div>

    <div class="chat-footer">
      <!-- 增强的工具栏 -->
      <ChatToolbar
        :config="chatStore.config"
        :current-session-id="chatStore.currentSessionId || ''"
        :user-id="userStore.userId"
        :chat-messages="currentSessionMessages"
        :current-session-title="currentSession?.title || ''"
        @update:config="chatStore.updateConfig($event)"
        @clear-messages="chatStore.clearCurrentSession"
        @image-upload="triggerFileInput"
        @document-upload="handleDocumentUpload"
        @update-session-title="chatStore.updateSessionTitle"
        @template-selected="handleTemplateSelected"
      />

      <input ref="fileInputRef" type="file" accept="image/*" style="display:none" @change="onFileChange" />

      <div class="footer-input-group">
        <n-input-group class="footer-input-group-inner">
          <n-input
            v-model:value="inputMessage"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="在这里输入消息，按 Enter 发送，Alt+Enter 换行..."
            @keydown="handleInputKeydown"
            class="footer-input"
            :disabled="chatStore.isLoading || chatStore.isStreaming"
          />
          <n-button
            type="primary"
            class="footer-btn"
            @click="handleButtonClick"
            :loading="chatStore.isStreaming"
            :disabled="chatStore.isStreaming"
          >
            <template #icon>
              <n-icon v-if="chatStore.isStreaming">
                <CloseOutline />
              </n-icon>
              <n-icon v-else>
                <SendOutline />
              </n-icon>
            </template>
            <span v-if="!chatStore.isStreaming">发送</span>
            <span v-else>终止</span>
          </n-button>
        </n-input-group>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NIcon, NInput, NAlert, useMessage } from 'naive-ui'
import { CloseOutline, SendOutline, DocumentTextOutline, AddOutline, TrashOutline } from '@vicons/ionicons5'
import ChatMessage from '../components/ChatMessage.vue'
import ChatToolbar from '../components/ChatToolbar.vue'
import { useChatStore } from '../stores/chat'
import { usePromptStore } from '../../shared/stores/prompt'
import { useImageUpload } from '../../image/composables/useImageUpload'
import { useMarkdownRender } from '../../shared/composables/useMarkdownRender'
import { useUserStore } from '../../auth/stores/user'
import { useModelStore } from '../../shared/stores/model'
import { useSessionManager } from '../../chat/composables/useSessionManager'  
import '../../../assets/css/ChatWindow.css'

const userStore = useUserStore()
const modelStore = useModelStore()
const chatStore = useChatStore()
const promptStore = usePromptStore()
const router = useRouter()
const { createAndActivateSession, initializeSessions } = useSessionManager()
const message = useMessage()

// 使用chatStore中的状态和方法
const currentSessionMessages = computed(() => chatStore.currentSessionMessages || [])
const currentSession = computed(() => chatStore.sessions?.find(s => s.id === chatStore.currentSessionId))
const hasError = computed(() => !!chatStore.error)

const {
  selectedImages,
  fileInputRef,
  removeImage,
  clearImages,
  triggerFileInput,
  onFileChange
} = useImageUpload({
  maxCount: 3,
  maxSize: 5 * 1024 * 1024
})
const { renderMarkdown } = useMarkdownRender()

// 基础状态
const inputMessage = ref('')
const chatBodyRef = ref<HTMLElement>()

const knowledgeId = ref<number | undefined>(undefined)
const selectedDocuments = ref<string[]>([])  // 存储文档base64数据
const selectedDocumentNames = ref<string[]>([])  // 存储文档文件名
// 使用ChatStore中的selectedTemplateId，不再需要本地状态
const showSessionSidebar = ref(false)  // 会话侧边栏显示状态

// 计算属性


// 时间格式化函数
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 方法
let scrollTimeout: number | null = null
const scrollToBottom = async (force: boolean = false) => {
  if (scrollTimeout) {
    clearTimeout(scrollTimeout)
  }

  scrollTimeout = window.setTimeout(async () => {
    await nextTick()
    if (chatBodyRef.value) {
      const container = chatBodyRef.value
      const scrollHeight = container.scrollHeight
      const clientHeight = container.clientHeight
      const maxScrollTop = scrollHeight - clientHeight
      
      // 强制滚动或流式输出时始终滚动到底部
      if (force || chatStore.isStreaming || maxScrollTop > 0) {
        container.scrollTo({
          top: maxScrollTop,
          behavior: chatStore.isStreaming ? 'auto' : 'smooth' // 流式输出时无动画，避免闪烁
        })
      }
    }
  }, 10) // 最小延迟，确保DOM更新完成
}

// 处理按钮点击事件
const handleButtonClick = async () => {
  if (chatStore.isStreaming) {
    console.log('[ChatWindow] 用户点击终止按钮');
    await chatStore.stopStreaming()
    
    // 强制触发UI更新，确保按钮状态正确
    await nextTick()
    await nextTick()
  } else {
    await sendMessage()
  }
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message) return
  
  // 清空输入和上传的文件
  clearImages()
  selectedDocuments.value = []
  selectedDocumentNames.value = []
  
  // 计算contentIndex：获取当前会话的消息数量
  const sessionMessages = currentSessionMessages.value
  const contentIndex = sessionMessages.length === 0 ? 0 : sessionMessages.length + 1
  
  try {
    await chatStore.sendMessage(message, {
      modelId: Number(chatStore.config.currentModelId) || Number(chatStore.config.defaultModel), // 确保modelId是number类型
      temperature: chatStore.config.temperature,
      maxTokens: chatStore.config.maxTokens,
      topP: chatStore.config.topP,
      memory: chatStore.config.enableMemory,
      knowledgeId: knowledgeId.value,
      userId: userStore.userId,
      contentIndex: contentIndex,
      systemPromptId: promptStore.getSelectedTemplateId()
    })
    
    inputMessage.value = ''
    
    // 强制触发UI更新，确保按钮状态正确
    await nextTick()
    
    // 确保滚动到底部
    await scrollToBottom(true)
    
  } catch (error) {
    console.error('发送消息失败:', error);
  }
}

// 键盘事件处理
const handleInputKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !e.altKey) {
    e.preventDefault()
    sendMessage()
  } else if (e.key === 'Enter' && e.altKey) {
    // Alt+Enter 插入换行
    e.preventDefault()
    const textarea = e.target as HTMLTextAreaElement
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const value = textarea.value
    textarea.value = value.substring(0, start) + '\n' + value.substring(end)
    textarea.selectionStart = textarea.selectionEnd = start + 1
    inputMessage.value = textarea.value
  }
}

// 文档上传处理
const handleDocumentUpload = (documents: string[], documentNames: string[]) => {
  selectedDocuments.value = [...selectedDocuments.value, ...documents]
  selectedDocumentNames.value = [...selectedDocumentNames.value, ...documentNames]
}

// 处理提示词模板选择
const handleTemplateSelected = (templateId: number | null) => {
  // 使用promptStore中的方法保存聊天提示词模板ID
  promptStore.saveSelectedTemplateId(templateId)
}

// 创建新会话
const handleCreateNewSession = async () => {
  try {
    await createAndActivateSession()
  } catch (error) {
    console.error('创建新会话失败:', error);
    message.error('创建新会话失败');
  }
}

// 消息操作
const handleResendMessage = (messageId: string, contentIndex?: number) => {
  if (chatStore.isStreaming) return
  chatStore.resendMessage(messageId, contentIndex)
}

const handleEditMessage = (messageId: string, newContent: string) => {
  if (chatStore.isStreaming) return
  chatStore.editMessage(messageId, newContent)
}

const handleEditMessageSubmit = (messageId: string, newContent: string) => {
  if (chatStore.isStreaming) return
  chatStore.editMessage(messageId, newContent)
}

const handleUpdateMessageStatus = (messageId: string, status: string) => {
    console.log('[ChatWindow] 更新消息状态', { messageId, status });
  
  // 查找消息并更新状态
  const message = currentSessionMessages.value.find(msg => msg.id === messageId)
  if (message) {
    // 验证status值是否有效
    if (['error', 'thinking', 'streaming', 'completed'].includes(status)) {
      message.status = status as 'error' | 'thinking' | 'streaming' | 'completed'
      if (status === 'streaming') {
        message.isStreaming = true
      }
    }
    
    // 强制触发UI更新
    nextTick()
    nextTick()
    
    // 触发强制内容更新事件
    window.dispatchEvent(new CustomEvent('force-content-update', {
      detail: { messageId }
    }) as any)
  }
}

// 生命周期
onMounted(async () => {
  // 从Pinia获取会话信息
  const userStore = useUserStore()
  
  // 确保用户状态已初始化
  await userStore.initUserState()
  
  // 初始化会话状态
  await initializeSessions({ loadFromRoute: true })

  // 从modelStore中恢复模型选择
  const savedModelId = modelStore.currentChatModel
  if (savedModelId) {
    chatStore.config.currentModelId = Number(savedModelId)
  }

  // 同步消息到全局，方便调试
  ;(window as any).__chat_messages__ = chatStore.messages;

  // 监听会话变化
  (window as any).addEventListener('sessionChange', (e: any) => {
    chatStore.switchSession(e.detail)
  })

  // 监听路由变化，当路由参数中的sessionId变化时重新加载会话
  watch(() => router.currentRoute.value.params.sessionId, (newSessionId) => {
    if (newSessionId && typeof newSessionId === 'string') {
      chatStore.switchSession(newSessionId)
    }
  })

  // 加载当前会话 - 优先使用路由参数中的sessionId
  const routeSessionId = router.currentRoute.value.params.sessionId
  if (routeSessionId && typeof routeSessionId === 'string') {
    // 如果路由参数中有sessionId，直接切换到该会话
    await chatStore.switchSession(routeSessionId)
    // 确保加载会话消息
    if (chatStore.currentSessionId === routeSessionId) {
      await chatStore.loadSessionMessagesFromBackend(routeSessionId)
    }
  } else if (userStore.currentSessionId) {
    // 如果路由参数中没有sessionId，但Pinia中有，则使用Pinia中的sessionId
    await chatStore.switchSession(userStore.currentSessionId)
    // 确保加载会话消息
    if (chatStore.currentSessionId === userStore.currentSessionId) {
      await chatStore.loadSessionMessagesFromBackend(userStore.currentSessionId)
    }
  } else {
    // 尝试从后端获取会话列表
    try {
      await chatStore.loadSessionsFromBackend(userStore.userId || 0)
      
      if (chatStore.sessions.length > 0) {
        // 如果有会话列表，使用最近的一个会话
        const latestSession = chatStore.sessions.sort((a, b) => b.lastActiveAt - a.lastActiveAt)[0]
        await chatStore.switchSession(latestSession.id)
        // 确保加载会话消息
        if (chatStore.currentSessionId === latestSession.id) {
          await chatStore.loadSessionMessagesFromBackend(latestSession.id)
        }
      } else {
        // 新用户，显示欢迎消息
        chatStore.clearCurrentMessages()
      }
    } catch (error) {
      console.error('加载会话列表失败:', error);
      // 加载失败，显示欢迎消息
      chatStore.clearCurrentMessages()
    }
  }

  // 确保初始加载后滚动到底部
  nextTick(() => {
    scrollToBottom(true)
  })
})

onUnmounted(() => {
  if (scrollTimeout) {
    clearTimeout(scrollTimeout)
  }
})

// 监听modelStore中的currentChatModel变化，同步更新聊天配置
watch(() => modelStore.currentChatModel, (newModelId) => {
  if (newModelId) {
    chatStore.config.currentModelId = Number(newModelId)
  }
}, { immediate: true })

// 监听配置变化
watch(() => chatStore.config.currentModelId, (newModelId) => {
  if (newModelId) {
    modelStore.setCurrentModelId(Number(newModelId))
  }
})

// 监听消息变化 - 新消息出现时强制滚动到底部
watch(chatStore.messages, (newMessages, oldMessages) => {
  if (newMessages.length > oldMessages?.length) {
    scrollToBottom(true) // 强制滚动，确保新消息可见
  }
  (window as any).__chat_messages__ = chatStore.messages
}, { deep: true })

// 监听流式输出状态变化
watch(() => chatStore.isStreaming, async (newVal, oldVal) => {
      console.log('[ChatWindow] 流式状态变化', { 
        oldVal,
        newVal,
        messageCount: currentSessionMessages.value.length
      });
  
  if (newVal) {
    // 开始流式输出时立即滚动到底部
    scrollToBottom(true)
  }
  
  // 强制触发UI更新，确保按钮状态正确
  await nextTick();
  
  // 再次强制触发UI更新，确保按钮状态正确
  await nextTick();
}, { immediate: true })

// 监听消息状态变化，确保状态更新时UI也能正确更新
watch(() => currentSessionMessages.value, (messages) => {
  // 检查是否有消息状态变化
  const hasStatusChange = messages.some(msg => 
    msg.status === 'streaming' || msg.isStreaming === true
  )
  
  if (hasStatusChange) {
    console.log('[ChatWindow] 检测到消息状态变化，强制滚动到底部并触发UI更新');
    // 有状态变化时，强制滚动到底部并触发UI更新
    scrollToBottom(true)
    
    // 确保UI更新
    nextTick(() => {
      console.log('[ChatWindow] 消息状态变化后UI更新完成', {
        isStreaming: chatStore.isStreaming,
        messageCount: currentSessionMessages.value.length,
        timestamp: new Date().toISOString()
      });
    });
    
    // 再次确保UI更新
    nextTick(() => {
      console.log('[ChatWindow] 消息状态变化后再次UI更新完成', {
        isStreaming: chatStore.isStreaming
      });
    });
  }
  
  // 检查是否有消息状态为streaming但内容为空的情况
  const streamingWithEmptyContent = messages.find(msg => 
    (msg.status === 'streaming' || msg.isStreaming === true) && 
    (!msg.content || msg.content.trim() === '')
  );
  
  if (streamingWithEmptyContent) {
    console.warn('[ChatWindow] 检测到流式状态但内容为空的消息，强制更新UI', {
      messageId: streamingWithEmptyContent.id,
      status: streamingWithEmptyContent.status,
      isStreaming: streamingWithEmptyContent.isStreaming,
      contentLength: streamingWithEmptyContent.content ? streamingWithEmptyContent.content.length : 0,
      timestamp: new Date().toISOString()
    });
    
    // 强制触发UI更新
    nextTick(() => {
      nextTick(() => {
        console.log('[ChatWindow] 流式状态但内容为空的消息UI更新完成');
      });
    });
  }
}, { deep: true, immediate: true })

// 监听消息状态变化，特别关注从thinking到streaming的变化
watch(() => currentSessionMessages.value.map(msg => ({ 
  id: msg.id, 
  status: msg.status, 
  isStreaming: msg.isStreaming 
})), (newStatuses, oldStatuses) => {
  if (!oldStatuses) return
  
  // 检查是否有消息从thinking状态变为streaming状态
  for (let i = 0; i < newStatuses.length; i++) {
    const newStatus = newStatuses[i]
    const oldStatus = oldStatuses.find(s => s.id === newStatus.id)
    
    if (oldStatus && oldStatus.status === 'thinking' && newStatus.status === 'streaming') {
      // 状态从thinking变为streaming，强制滚动到底部
      scrollToBottom(true)
      break
    }
  }
}, { deep: true, immediate: true })

// 监听消息内容变化，确保内容更新时状态也同步更新
watch(() => currentSessionMessages.value.map(msg => ({ 
  id: msg.id, 
  content: msg.content,
  status: msg.status,
  isStreaming: msg.isStreaming
})), async (newMessages, oldMessages) => {
  if (!oldMessages) return
  
  // 检查是否有消息内容变化但状态仍为thinking
  for (let i = 0; i < newMessages.length; i++) {
    const newMsg = newMessages[i]
    const oldMsg = oldMessages.find(m => m.id === newMsg.id)
    
    if (oldMsg && newMsg.content && newMsg.content.trim() && 
        newMsg.content !== oldMsg.content && newMsg.status === 'thinking') {
      // 内容变化但状态仍为thinking，强制更新状态为streaming
      const message = currentSessionMessages.value.find(m => m.id === newMsg.id)
      if (message) {
        console.log('[ChatWindow] 强制更新消息状态为streaming', { 
          messageId: message.id,
          reason: '内容变化但状态仍为thinking',
          contentLength: message.content.length
        });
        message.status = 'streaming'
        message.isStreaming = true
        
        // 确保全局状态也同步更新
        // 注意：chatStore.isStreaming 是只读属性，不能直接修改
        // 这里我们只更新消息状态，让系统自动处理流式状态
        
        // 强制多次UI更新，确保内容实时显示
        for (let j = 0; j < 5; j++) {
          await nextTick()
        }
        
        console.log('[ChatWindow] 强制更新消息状态后UI更新完成', {
          messageId: message.id,
          isStreaming: chatStore.isStreaming
        });
      }
    }
    
    // 检查是否有消息内容变化但状态不是streaming
    if (oldMsg && newMsg.content && newMsg.content.trim() && 
        newMsg.content !== oldMsg.content && newMsg.status !== 'streaming' && newMsg.status !== 'completed') {
      // 内容变化但状态不是streaming，强制更新状态为streaming
      const message = currentSessionMessages.value.find(m => m.id === newMsg.id)
      if (message) {
        console.log('[ChatWindow] 强制更新消息状态为streaming（内容变化）', { 
          messageId: message.id,
          reason: '内容变化但状态不是streaming',
          currentStatus: message.status,
          contentLength: message.content.length
        });
        message.status = 'streaming'
        message.isStreaming = true
        
        // 确保全局状态也同步更新
        // 注意：chatStore.isStreaming 是只读属性，不能直接修改
        // 这里我们只更新消息状态，让系统自动处理流式状态
        
        // 强制多次UI更新
        for (let j = 0; j < 3; j++) {
          await nextTick()
        }
        
        console.log('[ChatWindow] 强制更新消息状态后UI更新完成（内容变化）', {
          messageId: message.id,
          isStreaming: chatStore.isStreaming
        });
      }
    }
    
    // 如果状态已经是streaming且内容在变化，也强制更新UI
    if (oldMsg && newMsg.content && newMsg.content.trim() && 
        newMsg.content !== oldMsg.content && (newMsg.status === 'streaming' || newMsg.isStreaming)) {
      console.log('[ChatWindow] 流式状态下消息内容变化，强制更新UI', {
        messageId: newMsg.id,
        contentLength: newMsg.content.length
      });
      // 强制多次UI更新
      for (let j = 0; j < 3; j++) {
        await nextTick()
      }
      
      // 强制触发内容变化事件，确保ChatMessage组件能检测到变化
      const contentChangeEvent = new CustomEvent('force-content-update', {
        detail: { messageId: newMsg.id }
      }) as any;
      window.dispatchEvent(contentChangeEvent);
    }
  }
}, { deep: true, immediate: true })

// 定义emits
const emit = defineEmits(['updateSessionTitle', 'newSession'])

const removeDocument = (index: number) => {
  selectedDocuments.value.splice(index, 1)
  selectedDocumentNames.value.splice(index, 1)
}

const getDocumentName = (doc: string) => {
  // 使用存储的文件名，如果没有则显示为"文档1", "文档2"等
  const index = selectedDocuments.value.indexOf(doc)
  return selectedDocumentNames.value[index] || `文档${index + 1}`
}
</script>
